// src/directives/auth.directive.ts
import { useAppStore } from '@/store';
import { Directive, DirectiveBinding } from 'vue';

const authDirective: Directive = {
    mounted(el: HTMLElement, binding: DirectiveBinding<string | Array<string> | number | Array<number>>) {
        checkPermissionDirective(el, binding);
    },
    updated(el: HTMLElement, binding: DirectiveBinding<string | Array<string> | number | Array<number>>) {
        checkPermissionDirective(el, binding);
    },
};

export const checkPermission = function (permission: string | Array<string> | number | Array<number>): boolean {
    if (!permission) {
        return true;
    }
    if (Array.isArray(permission)) {
        if (permission.length == 0) {
            return true;
        }
        permission = permission.filter(x=>x).map(x => x.toString());
    } else if (typeof permission == 'number') {
        permission = permission.toString();
    }

    let hasPermission = false;
    const appStore = useAppStore();
    const userPermissions = appStore.contextUser.permissions || [];

    if (Array.isArray(permission)) {
        // 传入的是权限数组，检查用户是否有任一权限
        hasPermission = permission.some(permission => userPermissions.includes(permission));
    } else {
        // 传入的是单个权限字符串
        hasPermission = userPermissions.includes(permission);
    }
    return hasPermission;
}

function checkPermissionDirective(el: HTMLElement, binding: DirectiveBinding<string | Array<string> | number | Array<number>>) {
    const { value } = binding;

    if (!value) {
        throw new Error('请传入权限值，如 v-auth="\'view_dashboard\'" 或 v-auth="[\'edit_user\', \'delete_post\']"');
    }

    const hasPermission = checkPermission(value);

    if (!hasPermission) {
        el.parentNode?.removeChild(el);
    }
}

export default authDirective;